package my.edu.model.User.service;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import my.edu.common.config.ThreadPoolConfig;
import my.edu.model.User.entity.VO.MenuItem;
import org.springframework.stereotype.Service;
import my.edu.model.User.entity.PermissionMenu;
import my.edu.model.User.mapper.PermissionMenuMapper;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
public class PermissionMenuServiceImpl extends ServiceImpl<PermissionMenuMapper, PermissionMenu> implements IPermissionMenuService {

    private final ThreadPoolConfig threadPoolConfig;

    public PermissionMenuServiceImpl(ThreadPoolConfig threadPoolConfig) {
        this.threadPoolConfig = threadPoolConfig;
    }

    @Override
    public List<PermissionMenu> getByPermissionIds(List<Long> permissionList) {
        List<PermissionMenu> list = lambdaQuery()
                .in(PermissionMenu::getPermissionId, permissionList)
                .or()
                .eq(PermissionMenu::getPermissionId, 0)
                .list();
        return list;
    }

    @Override
    @Transactional
    public void updateMenuSort(List<MenuItem> menuList, Long par) {
        for (int i = 0; i < menuList.size(); i++) {
            MenuItem menuItem = menuList.get(i);
            menuItem.setSort(i);
            menuItem.setParentId(par);
            if (menuItem.getChildren() != null) {
                updateMenuSort(menuItem.getChildren(), menuItem.getId());
            }
        }

        //将menuList中的children提取出来，合并到List<PermissionMenu>
        List<PermissionMenu> permissionMenuList = new ArrayList<>();
        extractAndMergeMenus(menuList, permissionMenuList);

        List<PermissionMenu> Olist = list();
        for (PermissionMenu permissionMenu : permissionMenuList) {
            PermissionMenu OMenu = Olist.stream().filter(pm -> pm.getId().equals(permissionMenu.getId())).findFirst().orElse(null);
            if (OMenu != null) {
                OMenu.setSort(permissionMenu.getSort());
                OMenu.setParentId(permissionMenu.getParentId());
            }
        }
        updateBatchById(Olist);

    }

    private void extractAndMergeMenus(List<MenuItem> menuList, List<PermissionMenu> permissionMenuList) {
        for (MenuItem menuItem : menuList) {
            // 将 MenuItem 转换为 PermissionMenu
            PermissionMenu permissionMenu = BeanUtil.copyProperties(menuItem, PermissionMenu.class, "children");
            permissionMenuList.add(permissionMenu);

            // 递归处理子菜单
            if (menuItem.getChildren() != null && !menuItem.getChildren().isEmpty()) {
                extractAndMergeMenus(menuItem.getChildren(), permissionMenuList);
            }
        }
    }
}
